package br.gendi.rcp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.part.ViewPart;

import br.gendi.beans.BaseGenomica;
import br.gendi.core.Util;
import br.gendi.dialog.ConfiguracoesBases;

public class NavigationView extends ViewPart {

	public static final String ID = "br.gendi.rcp.navigationView";

	private ToolBar toolBar = null;
	private Composite p = null;
	private String nomeSelecionado = "";
	private Menu m;

	public void createPartControl(final Composite parent) {
		p = parent;
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = false;
		gridData.verticalAlignment = GridData.BEGINNING;

		toolBar = new ToolBar(parent, SWT.FLAT | SWT.WRAP);
		toolBar.setLayoutData(gridData);
		toolBar.setFont(new Font(parent.getDisplay(),"Tahoma",7 , SWT.NONE));
		try {
			carregarItens();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}

		parent.getShell().addListener(SWT.Resize, new Listener() {
			public void handleEvent(Event e) {
				Rectangle rect = parent.getShell().getClientArea();
				Point size = toolBar.computeSize(rect.width, SWT.DEFAULT);
				toolBar.setSize(size);
			}
		});	
	}

	public void removerItens() {
		ToolItem tt = null;
		while (toolBar.getItemCount() != 0) {
			tt = toolBar.getItem(0);
			tt.dispose();
			tt = null;
			toolBar.update();
			toolBar.redraw();
		}
		toolBar.update();
		toolBar.redraw();
	}

	public void carregarItens() throws FileNotFoundException, IOException, ClassNotFoundException {
		removerItens();

		File f = new File(Util.SAVE_PATH);
		//System.out.println(f.getAbsolutePath());
		if (!f.exists()) {
			f.mkdirs();
			return;
		}
		File lista[] = f.listFiles();

		if (lista == null || lista.length == 0)
			return;

		ToolItem toolItem1 = null;
		//System.out.println("--->"+lista.length);
		m = new Menu(p);
		for (int i=0; i<lista.length; i++) 
		{
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(lista[i])); 
			final BaseGenomica base = (BaseGenomica)in.readObject();
			toolItem1 = new ToolItem(toolBar, SWT.PUSH);
			in.close();

			toolBar.addMouseListener(new MouseListener() {
				@Override
				public void mouseDoubleClick(MouseEvent arg0) {

				}
				@Override
				public void mouseDown(MouseEvent arg0) {
					if (arg0.button!=3)
						return;
					ToolItem item = toolBar.getItem(new Point(arg0.x, arg0.y));
					if (item != null) {
						if (m.isVisible()) {
							return;
						} else {
							m = new Menu(p);
						}
						
						MenuItem miMain = new MenuItem(m, SWT.NONE);
						miMain.setText(item.getToolTipText());
						miMain.setEnabled(false);
						
						new MenuItem(m, SWT.SEPARATOR);
						
						MenuItem mi = new MenuItem(m, SWT.NONE);
						mi.setText("Habilitar");
						mi.setImage(new Image(p.getDisplay(),br.gendi.rcp.Activator.getImageDescriptor("/icons/checkbox.png").getImageData()));
						mi.addSelectionListener(new SelectionListener() {
							@Override
							public void widgetDefaultSelected(SelectionEvent arg0) {
							}

							@Override
							public void widgetSelected(SelectionEvent arg0) {
								try {
									BaseGenomica base = Util.getBasePorNome(nomeSelecionado);
									if (base == null)
										return;
									base.setAtivo(true);
									base.salvarConfiguracao();
									carregarItens();
								} catch (FileNotFoundException e) {	e.printStackTrace();
								} catch (IOException e) { e.printStackTrace();
								} catch (ClassNotFoundException e) { e.printStackTrace();	}
							}
						});
						nomeSelecionado = item.getToolTipText();
						MenuItem mi2 = new MenuItem(m, SWT.NONE);
						mi2.setText("Desabilitar");
						mi2.setImage(new Image(p.getDisplay(),br.gendi.rcp.Activator.getImageDescriptor("/icons/nocheckbox.png").getImageData()));
						mi2.addSelectionListener(new SelectionListener() {

							@Override
							public void widgetDefaultSelected(SelectionEvent arg0) {
							}

							@Override
							public void widgetSelected(SelectionEvent arg0) {
								try {
									BaseGenomica base = Util.getBasePorNome(nomeSelecionado);
									if (base == null)
										return;
									base.setAtivo(false);
									base.salvarConfiguracao();
									carregarItens();
								} catch (FileNotFoundException e) {	e.printStackTrace();
								} catch (IOException e) { e.printStackTrace();
								} catch (ClassNotFoundException e) { e.printStackTrace();	}
							}
						});
						
						MenuItem mi4 = new MenuItem(m, SWT.NONE);
						mi4.setText("Copiar");
						mi4.setImage(new Image(p.getDisplay(),br.gendi.rcp.Activator.getImageDescriptor("/icons/copy.png").getImageData()));
						mi4.addSelectionListener(new SelectionListener() {

							@Override
							public void widgetDefaultSelected(SelectionEvent arg0) {
							}

							@Override
							public void widgetSelected(SelectionEvent arg0) {
								BaseGenomica base = null;
								try {
									base = Util.getBasePorNome(nomeSelecionado);
									if (base == null) {
										return;
									}
									base.copiarConfiguracao();
									carregarItens();
								} catch (FileNotFoundException e) {	e.printStackTrace();
								} catch (IOException e) { e.printStackTrace();
								} catch (ClassNotFoundException e) { e.printStackTrace();
								}
								
							}
						});

						new MenuItem(m, SWT.SEPARATOR);

						MenuItem mi3 = new MenuItem(m, SWT.NONE);
						mi3.setText("Remover");
						mi3.setImage(new Image(p.getDisplay(),br.gendi.rcp.Activator.getImageDescriptor("/icons/trash.png").getImageData()));
						mi3.addSelectionListener(new SelectionListener() {

							@Override
							public void widgetDefaultSelected(SelectionEvent arg0) {
							}

							@Override
							public void widgetSelected(SelectionEvent arg0) {
								BaseGenomica base;
								try {
									base = Util.getBasePorNome(nomeSelecionado);
									if (base == null) {
										return;
									}
									boolean remover = MessageDialog.openQuestion(p.getShell(), "EPIDI", "Tem certeza que gostaria de remover esta configuração ?");
									if (remover == false)
										return;
									
									base.removerConfiguracao();
									carregarItens();
									m.setVisible(false);
								} catch (FileNotFoundException e) {	e.printStackTrace();
								} catch (IOException e) { e.printStackTrace();
								} catch (ClassNotFoundException e) { e.printStackTrace();
								}
								
							}
						});

						int posX = p.getShell().getDisplay().getCursorLocation().x;
						int posY = p.getShell().getDisplay().getCursorLocation().y;
						m.setLocation(posX , posY );
						m.setVisible(true);
					}
				}
				@Override
				public void mouseUp(MouseEvent arg0) {

				}
			});

			if (base.getTitulo().length() > 20)
				toolItem1.setText(base.getTitulo().substring(0, 17) + "..");
			else
				toolItem1.setText(base.getTitulo());

			toolItem1.setToolTipText(base.getTitulo());
			if (base.isAtivo())
				toolItem1.setImage(new Image(Display.getCurrent(), br.gendi.rcp.Activator.getImageDescriptor("/images/dnadna.png").getImageData()));
			else
				toolItem1.setImage(new Image(Display.getCurrent(), br.gendi.rcp.Activator.getImageDescriptor("/images/dnadna-disabled.png").getImageData()));

			toolItem1.addSelectionListener(new SelectionListener() {
				public void widgetDefaultSelected(SelectionEvent arg0) {
				}
				public void widgetSelected(SelectionEvent arg0) {
					ConfiguracoesBases c = new ConfiguracoesBases(base);
				}
			});

		}
	}

	public void habilitarTodos(boolean habilitado) {
		File f = new File(Util.SAVE_PATH);
		if (!f.exists()) {
			f.mkdirs();
			return;
		}
		File lista[] = f.listFiles();
		File f2 = null;

		if (lista == null || lista.length == 0)
			return;

		for (int i=0; i<lista.length; i++) 
		{
			ObjectInputStream in = null;
			try {
				in = new ObjectInputStream(new FileInputStream(lista[i]));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
			BaseGenomica base = null;
			try {
				base = (BaseGenomica)in.readObject();
				in.close();
				base.setAtivo(habilitado);
				f2 = new File(Util.SAVE_PATH + base.getTitulo());
				ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f2)); 
				out.writeObject(base);
				out.flush();
				out.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}						
		}
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		//viewer.getControl().setFocus();
	}
}